home *** CD-ROM | disk | FTP | other *** search
/ The Fatted Calf / The Fatted Calf.iso / Applications / Developer / BBFig / Source / regex.c < prev    next >
C/C++ Source or Header  |  1991-11-15  |  46KB  |  1,807 lines

  1. /* Extended regular expression matching and search library.
  2.    Copyright (C) 1985, 1989 Free Software Foundation, Inc.
  3.   
  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 1, or (at your option)
  7.    any later version.
  8.   
  9.    This program is distributed in the hope that it will be useful,
  10.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  11.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12.    GNU General Public License for more details.
  13.   
  14.    You should have received a copy of the GNU General Public License
  15.    along with this program; if not, write to the Free Software
  16.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  17.   
  18.   
  19.    In other words, you are welcome to use, share and improve this program.
  20.    You are forbidden to forbid anyone else to use, share and improve
  21.    what you give them.   Help stamp out software-hoarding!  */
  22.  
  23.  
  24. /* To test, compile with -Dtest.
  25.  This Dtestable feature turns this into a self-contained program
  26.  which reads a pattern, describes how it compiles,
  27.  then reads a string and searches for it.  */
  28.  
  29. #include <string.h>
  30. #include <stdlib.h>
  31.  
  32. #ifdef emacs
  33.  
  34. /* The `emacs' switch turns on certain special matching commands
  35.  that make sense only in emacs. */
  36.  
  37. #include "config.h"
  38. #include "lisp.h"
  39. #include "buffer.h"
  40. #include "syntax.h"
  41.  
  42. #else                /* not emacs */
  43.  
  44. #ifdef USG
  45. #define bcopy(s,d,n)    memcpy((d),(s),(n))
  46. #define bcmp(s1,s2,n)    memcmp((s1),(s2),(n))
  47. #define bzero(s,n)    memset((s),0,(n))
  48. #endif
  49.  
  50. /* Make alloca work the best possible way.  */
  51. #ifdef __GNUC__
  52. /*#define alloca __builtin_alloca */
  53. #else
  54. #ifdef sparc
  55. #include <alloca.h>
  56. #endif
  57. #endif
  58.  
  59. /*
  60.  * Define the syntax stuff, so we can do the \<...\> things.
  61.  */
  62.  
  63. #ifndef Sword            /* must be non-zero in some of the tests
  64.                  * below... */
  65. #define Sword 1
  66. #endif
  67.  
  68. #define SYNTAX(c) re_syntax_table[c]
  69.  
  70. #ifdef SYNTAX_TABLE
  71.  
  72. char               *re_syntax_table;
  73.  
  74. #else
  75.  
  76. static char         re_syntax_table[256];
  77.  
  78. static void
  79. init_syntax_once()
  80. {
  81.     register int        c;
  82.     static int          done = 0;
  83.  
  84.     if (done)
  85.     return;
  86.  
  87.     bzero(re_syntax_table, sizeof re_syntax_table);
  88.  
  89.     for (c = 'a'; c <= 'z'; c++)
  90.     re_syntax_table[c] = Sword;
  91.  
  92.     for (c = 'A'; c <= 'Z'; c++)
  93.     re_syntax_table[c] = Sword;
  94.  
  95.     for (c = '0'; c <= '9'; c++)
  96.     re_syntax_table[c] = Sword;
  97.  
  98.     done = 1;
  99. }
  100.  
  101. #endif                /* SYNTAX_TABLE */
  102. #endif                /* not emacs */
  103.  
  104. #include "regex.h"
  105.  
  106. /* Number of failure points to allocate space for initially,
  107.  when matching.  If this number is exceeded, more space is allocated,
  108.  so it is not a hard limit.  */
  109.  
  110. #ifndef NFAILURES
  111. #define NFAILURES 80
  112. #endif                /* NFAILURES */
  113.  
  114.  
  115. #ifndef SIGN_EXTEND_CHAR
  116. #define SIGN_EXTEND_CHAR(x) (x)
  117. #endif
  118.  
  119.  
  120. static int          obscure_syntax = 0;
  121.  
  122. /* Specify the precise syntax of regexp for compilation.
  123.    This provides for compatibility for various utilities
  124.    which historically have different, incompatible syntaxes.
  125.   
  126.    The argument SYNTAX is a bit-mask containing the two bits
  127.    RE_NO_BK_PARENS and RE_NO_BK_VBAR.  */
  128.  
  129. int
  130. re_set_syntax(syntax)
  131. int syntax;
  132. {
  133.     int                 ret;
  134.  
  135.     ret = obscure_syntax;
  136.     obscure_syntax = syntax;
  137.     return ret;
  138. }
  139.  
  140.  
  141. /* re_compile_pattern takes a regular-expression string
  142.    and converts it into a buffer full of byte commands for matching.
  143.   
  144.   PATTERN   is the address of the pattern string
  145.   SIZE      is the length of it.
  146.   BUFP        is a  struct re_pattern_buffer *  which points to the info
  147.         on where to store the byte commands.
  148.         This structure contains a  char *  which points to the
  149.         actual space, which should have been obtained with malloc.
  150.         re_compile_pattern may use  realloc  to grow the buffer space.
  151.   
  152.   The number of bytes of commands can be found out by looking in
  153.   the  struct re_pattern_buffer  that bufp pointed to,
  154.   after re_compile_pattern returns.
  155. */
  156.  
  157. #define PATPUSH(ch) (*b++ = (char) (ch))
  158.  
  159. #define PATFETCH(c) \
  160.  {if (p == pend) goto end_of_pattern; \
  161.   c = * (unsigned char *) p++; \
  162.   if (translate) c = translate[c]; }
  163.  
  164. #define PATFETCH_RAW(c) \
  165.  {if (p == pend) goto end_of_pattern; \
  166.   c = * (unsigned char *) p++; }
  167.  
  168. #define PATUNFETCH p--
  169.  
  170. #define EXTEND_BUFFER \
  171.   { char *old_buffer = bufp->buffer; \
  172.     if (bufp->allocated == (1<<16)) goto too_big; \
  173.     bufp->allocated *= 2; \
  174.     if (bufp->allocated > (1<<16)) bufp->allocated = (1<<16); \
  175.     if (!(bufp->buffer = (char *) realloc (bufp->buffer, bufp->allocated))) \
  176.       goto memory_exhausted; \
  177.     c = bufp->buffer - old_buffer; \
  178.     b += c; \
  179.     if (fixup_jump) \
  180.       fixup_jump += c; \
  181.     if (laststart) \
  182.       laststart += c; \
  183.     begalt += c; \
  184.     if (pending_exact) \
  185.       pending_exact += c; \
  186.   }
  187.  
  188. static int 
  189. store_jump(), insert_jump();
  190.  
  191. char               *
  192. re_compile_pattern(pattern, size, bufp)
  193.     char               *pattern;
  194.     int                 size;
  195.     struct re_pattern_buffer *bufp;
  196. {
  197.     register char      *b = bufp->buffer;
  198.     register char      *p = pattern;
  199.     char               *pend = pattern + size;
  200.     register unsigned   c, c1;
  201.     char               *p1;
  202.     unsigned char      *translate = (unsigned char *)bufp->translate;
  203.  
  204.  /*
  205.   * address of the count-byte of the most recently inserted "exactn" command.
  206.   * This makes it possible to tell whether a new exact-match character can be
  207.   * added to that command or requires a new "exactn" command. 
  208.   */
  209.  
  210.     char               *pending_exact = 0;
  211.  
  212.  /*
  213.   * address of the place where a forward-jump should go to the end of the
  214.   * containing expression. Each alternative of an "or", except the last, ends
  215.   * with a forward-jump of this sort. 
  216.   */
  217.  
  218.     char               *fixup_jump = 0;
  219.  
  220.  /*
  221.   * address of start of the most recently finished expression. This tells
  222.   * postfix * where to find the start of its operand. 
  223.   */
  224.  
  225.     char               *laststart = 0;
  226.  
  227.  /* In processing a repeat, 1 means zero matches is allowed */
  228.  
  229.     char                zero_times_ok;
  230.  
  231.  /* In processing a repeat, 1 means many matches is allowed */
  232.  
  233.     char                many_times_ok;
  234.  
  235.  /* address of beginning of regexp, or inside of last \( */
  236.  
  237.     char               *begalt = b;
  238.  
  239.  /*
  240.   * Stack of information saved by \( and restored by \). Four stack elements
  241.   * are pushed by each \(: First, the value of b. Second, the value of
  242.   * fixup_jump. Third, the value of regnum. Fourth, the value of begalt.  
  243.   */
  244.  
  245.     int                 stackb[40];
  246.     int                *stackp = stackb;
  247.     int                *stacke = stackb + 40;
  248.     int                *stackt;
  249.  
  250.  /*
  251.   * Counts \('s as they are encountered.  Remembered for the matching \),
  252.   * where it becomes the "register number" to put in the stop_memory command 
  253.   */
  254.  
  255.     int                 regnum = 1;
  256.  
  257.     bufp->fastmap_accurate = 0;
  258.  
  259. #ifndef emacs
  260. #ifndef SYNTAX_TABLE
  261.  /*
  262.   * Initialize the syntax table. 
  263.   */
  264.     init_syntax_once();
  265. #endif
  266. #endif
  267.  
  268.     if (bufp->allocated == 0) {
  269.     bufp->allocated = 28;
  270.     if (bufp->buffer)
  271.     /* EXTEND_BUFFER loses when bufp->allocated is 0 */
  272.         bufp->buffer = (char *)realloc(bufp->buffer, 28);
  273.     else
  274.     /* Caller did not allocate a buffer.  Do it for him */
  275.         bufp->buffer = (char *)malloc(28);
  276.     if (!bufp->buffer)
  277.         goto memory_exhausted;
  278.     begalt = b = bufp->buffer;
  279.     }
  280.     while (p != pend) {
  281.     if (b - bufp->buffer > bufp->allocated - 10)
  282.     /* Note that EXTEND_BUFFER clobbers c */
  283.         EXTEND_BUFFER;
  284.  
  285.     PATFETCH(c);
  286.  
  287.     switch (c) {
  288.     case '$':
  289.         if (obscure_syntax & RE_TIGHT_VBAR) {
  290.         if (!(obscure_syntax & RE_CONTEXT_INDEP_OPS) && p != pend)
  291.             goto normal_char;
  292.         /* Make operand of last vbar end before this `$'.  */
  293.         if (fixup_jump)
  294.             store_jump(fixup_jump, jump, b);
  295.         fixup_jump = 0;
  296.         PATPUSH(endline);
  297.         break;
  298.         }
  299.     /*
  300.      * $ means succeed if at end of line, but only in special contexts.
  301.      * If randomly in the middle of a pattern, it is a normal character. 
  302.      */
  303.         if (p == pend || *p == '\n'
  304.         || (obscure_syntax & RE_CONTEXT_INDEP_OPS)
  305.         || (obscure_syntax & RE_NO_BK_PARENS
  306.             ? *p == ')'
  307.             : *p == '\\' && p[1] == ')')
  308.         || (obscure_syntax & RE_NO_BK_VBAR
  309.             ? *p == '|'
  310.             : *p == '\\' && p[1] == '|')) {
  311.         PATPUSH(endline);
  312.         break;
  313.         }
  314.         goto normal_char;
  315.  
  316.     case '^':
  317.     /*
  318.      * ^ means succeed if at beg of line, but only if no preceding
  319.      * pattern. 
  320.      */
  321.  
  322.         if (laststart && p[-2] != '\n'
  323.         && !(obscure_syntax & RE_CONTEXT_INDEP_OPS))
  324.         goto normal_char;
  325.         if (obscure_syntax & RE_TIGHT_VBAR) {
  326.         if (p != pattern + 1
  327.             && !(obscure_syntax & RE_CONTEXT_INDEP_OPS))
  328.             goto normal_char;
  329.         PATPUSH(begline);
  330.         begalt = b;
  331.         } else
  332.         PATPUSH(begline);
  333.         break;
  334.  
  335.     case '+':
  336.     case '?':
  337.         if (obscure_syntax & RE_BK_PLUS_QM)
  338.         goto normal_char;
  339.     handle_plus:
  340.     case '*':
  341.     /* If there is no previous pattern, char not special. */
  342.         if (!laststart && !(obscure_syntax & RE_CONTEXT_INDEP_OPS))
  343.         goto normal_char;
  344.     /*
  345.      * If there is a sequence of repetition chars, collapse it down to
  346.      * equivalent to just one.  
  347.      */
  348.         zero_times_ok = 0;
  349.         many_times_ok = 0;
  350.         while (1) {
  351.         zero_times_ok |= c != '+';
  352.         many_times_ok |= c != '?';
  353.         if (p == pend)
  354.             break;
  355.         PATFETCH(c);
  356.         if (c == '*');
  357.         else if (!(obscure_syntax & RE_BK_PLUS_QM)
  358.              && (c == '+' || c == '?'));
  359.         else if ((obscure_syntax & RE_BK_PLUS_QM)
  360.              && c == '\\') {
  361.             int                 c1;
  362.  
  363.             PATFETCH(c1);
  364.             if (!(c1 == '+' || c1 == '?')) {
  365.             PATUNFETCH;
  366.             PATUNFETCH;
  367.             break;
  368.             }
  369.             c = c1;
  370.         } else {
  371.             PATUNFETCH;
  372.             break;
  373.         }
  374.         }
  375.  
  376.     /*
  377.      * Star, etc. applied to an empty pattern is equivalent to an empty
  378.      * pattern.  
  379.      */
  380.         if (!laststart)
  381.         break;
  382.  
  383.     /*
  384.      * Now we know whether 0 matches is allowed, and whether 2 or more
  385.      * matches is allowed.  
  386.      */
  387.         if (many_times_ok) {
  388.         /*
  389.          * If more than one repetition is allowed, put in a backward jump
  390.          * at the end.  
  391.          */
  392.         store_jump(b, maybe_finalize_jump, laststart - 3);
  393.         b += 3;
  394.         }
  395.         insert_jump(on_failure_jump, laststart, b + 3, b);
  396.         pending_exact = 0;
  397.         b += 3;
  398.         if (!zero_times_ok) {
  399.         /*
  400.          * At least one repetition required: insert before the loop a
  401.          * skip over the initial on-failure-jump instruction 
  402.          */
  403.         insert_jump(dummy_failure_jump, laststart, laststart + 6, b);
  404.         b += 3;
  405.         }
  406.         break;
  407.  
  408.     case '.':
  409.         laststart = b;
  410.         PATPUSH(anychar);
  411.         break;
  412.  
  413.     case '[':
  414.         while (b - bufp->buffer
  415.            > bufp->allocated - 3 - (1 << BYTEWIDTH) / BYTEWIDTH)
  416.         /* Note that EXTEND_BUFFER clobbers c */
  417.         EXTEND_BUFFER;
  418.  
  419.         laststart = b;
  420.         if (*p == '^')
  421.         PATPUSH(charset_not), p++;
  422.         else
  423.         PATPUSH(charset);
  424.         p1 = p;
  425.  
  426.         PATPUSH((1 << BYTEWIDTH) / BYTEWIDTH);
  427.     /* Clear the whole map */
  428.         bzero(b, (1 << BYTEWIDTH) / BYTEWIDTH);
  429.     /* Read in characters and ranges, setting map bits */
  430.         while (1) {
  431.         PATFETCH(c);
  432.         if (c == ']' && p != p1 + 1)
  433.             break;
  434.         if (*p == '-' && p[1] != ']') {
  435.             PATFETCH(c1);
  436.             PATFETCH(c1);
  437.             while (c <= c1)
  438.             b[c / BYTEWIDTH] |= 1 << (c % BYTEWIDTH), c++;
  439.         } else {
  440.             b[c / BYTEWIDTH] |= 1 << (c % BYTEWIDTH);
  441.         }
  442.         }
  443.     /*
  444.      * Discard any bitmap bytes that are all 0 at the end of the map.
  445.      * Decrement the map-length byte too. 
  446.      */
  447.         while ((int)b[-1] > 0 && b[b[-1] - 1] == 0)
  448.         b[-1]--;
  449.         b += b[-1];
  450.         break;
  451.  
  452.     case '(':
  453.         if (!(obscure_syntax & RE_NO_BK_PARENS))
  454.         goto normal_char;
  455.         else
  456.         goto handle_open;
  457.  
  458.     case ')':
  459.         if (!(obscure_syntax & RE_NO_BK_PARENS))
  460.         goto normal_char;
  461.         else
  462.         goto handle_close;
  463.  
  464.     case '\n':
  465.         if (!(obscure_syntax & RE_NEWLINE_OR))
  466.         goto normal_char;
  467.         else
  468.         goto handle_bar;
  469.  
  470.     case '|':
  471.         if (!(obscure_syntax & RE_NO_BK_VBAR))
  472.         goto normal_char;
  473.         else
  474.         goto handle_bar;
  475.  
  476.     case '\\':
  477.         if (p == pend)
  478.         goto invalid_pattern;
  479.         PATFETCH_RAW(c);
  480.         switch (c) {
  481.         case '(':
  482.         if (obscure_syntax & RE_NO_BK_PARENS)
  483.             goto normal_backsl;
  484.     handle_open:
  485.         if (stackp == stacke)
  486.             goto nesting_too_deep;
  487.         if (regnum < RE_NREGS) {
  488.             PATPUSH(start_memory);
  489.             PATPUSH(regnum);
  490.         }
  491.         *stackp++ = b - bufp->buffer;
  492.         *stackp++ = fixup_jump ? fixup_jump - bufp->buffer + 1 : 0;
  493.         *stackp++ = regnum++;
  494.         *stackp++ = begalt - bufp->buffer;
  495.         fixup_jump = 0;
  496.         laststart = 0;
  497.         begalt = b;
  498.         break;
  499.  
  500.         case ')':
  501.         if (obscure_syntax & RE_NO_BK_PARENS)
  502.             goto normal_backsl;
  503.     handle_close:
  504.         if (stackp == stackb)
  505.             goto unmatched_close;
  506.         begalt = *--stackp + bufp->buffer;
  507.         if (fixup_jump)
  508.             store_jump(fixup_jump, jump, b);
  509.         if (stackp[-1] < RE_NREGS) {
  510.             PATPUSH(stop_memory);
  511.             PATPUSH(stackp[-1]);
  512.         }
  513.         stackp -= 2;
  514.         fixup_jump = 0;
  515.         if (*stackp)
  516.             fixup_jump = *stackp + bufp->buffer - 1;
  517.         laststart = *--stackp + bufp->buffer;
  518.         break;
  519.  
  520.         case '|':
  521.         if (obscure_syntax & RE_NO_BK_VBAR)
  522.             goto normal_backsl;
  523.     handle_bar:
  524.         insert_jump(on_failure_jump, begalt, b + 6, b);
  525.         pending_exact = 0;
  526.         b += 3;
  527.         if (fixup_jump)
  528.             store_jump(fixup_jump, jump, b);
  529.         fixup_jump = b;
  530.         b += 3;
  531.         laststart = 0;
  532.         begalt = b;
  533.         break;
  534.  
  535. #ifdef emacs
  536.         case '=':
  537.         PATPUSH(at_dot);
  538.         break;
  539.  
  540.         case 's':
  541.         laststart = b;
  542.         PATPUSH(syntaxspec);
  543.         PATFETCH(c);
  544.         PATPUSH(syntax_spec_code[c]);
  545.         break;
  546.  
  547.         case 'S':
  548.         laststart = b;
  549.         PATPUSH(notsyntaxspec);
  550.         PATFETCH(c);
  551.         PATPUSH(syntax_spec_code[c]);
  552.         break;
  553. #endif                /* emacs */
  554.  
  555.         case 'w':
  556.         laststart = b;
  557.         PATPUSH(wordchar);
  558.         break;
  559.  
  560.         case 'W':
  561.         laststart = b;
  562.         PATPUSH(notwordchar);
  563.         break;
  564.  
  565.         case '<':
  566.         PATPUSH(wordbeg);
  567.         break;
  568.  
  569.         case '>':
  570.         PATPUSH(wordend);
  571.         break;
  572.  
  573.         case 'b':
  574.         PATPUSH(wordbound);
  575.         break;
  576.  
  577.         case 'B':
  578.         PATPUSH(notwordbound);
  579.         break;
  580.  
  581.         case '`':
  582.         PATPUSH(begbuf);
  583.         break;
  584.  
  585.         case '\'':
  586.         PATPUSH(endbuf);
  587.         break;
  588.  
  589.         case '1':
  590.         case '2':
  591.         case '3':
  592.         case '4':
  593.         case '5':
  594.         case '6':
  595.         case '7':
  596.         case '8':
  597.         case '9':
  598.         c1 = c - '0';
  599.         if (c1 >= regnum)
  600.             goto normal_char;
  601.         for (stackt = stackp - 2; stackt > stackb; stackt -= 4)
  602.             if (*stackt == c1)
  603.             goto normal_char;
  604.         laststart = b;
  605.         PATPUSH(duplicate);
  606.         PATPUSH(c1);
  607.         break;
  608.  
  609.         case '+':
  610.         case '?':
  611.         if (obscure_syntax & RE_BK_PLUS_QM)
  612.             goto handle_plus;
  613.  
  614.         default:
  615.     normal_backsl:
  616.         /*
  617.          * You might think it would be useful for \ to mean not to
  618.          * translate; but if we don't translate it it will never match
  619.          * anything.  
  620.          */
  621.         if (translate)
  622.             c = translate[c];
  623.         goto normal_char;
  624.         }
  625.         break;
  626.  
  627.     default:
  628.     normal_char:
  629.         if (!pending_exact || pending_exact + *pending_exact + 1 != b
  630.         || *pending_exact == 0177 || *p == '*' || *p == '^'
  631.         || ((obscure_syntax & RE_BK_PLUS_QM)
  632.             ? *p == '\\' && (p[1] == '+' || p[1] == '?')
  633.             : (*p == '+' || *p == '?'))) {
  634.         laststart = b;
  635.         PATPUSH(exactn);
  636.         pending_exact = b;
  637.         PATPUSH(0);
  638.         }
  639.         PATPUSH(c);
  640.         (*pending_exact)++;
  641.     }
  642.     }
  643.  
  644.     if (fixup_jump)
  645.     store_jump(fixup_jump, jump, b);
  646.  
  647.     if (stackp != stackb)
  648.     goto unmatched_open;
  649.  
  650.     bufp->used = b - bufp->buffer;
  651.     return 0;
  652.  
  653. invalid_pattern:
  654.     return "Invalid regular expression";
  655.  
  656. unmatched_open:
  657.     return "Unmatched \\(";
  658.  
  659. unmatched_close:
  660.     return "Unmatched \\)";
  661.  
  662. end_of_pattern:
  663.     return "Premature end of regular expression";
  664.  
  665. nesting_too_deep:
  666.     return "Nesting too deep";
  667.  
  668. too_big:
  669.     return "Regular expression too big";
  670.  
  671. memory_exhausted:
  672.     return "Memory exhausted";
  673. }
  674.  
  675. /* Store where `from' points a jump operation to jump to where `to' points.
  676.   `opcode' is the opcode to store. */
  677.  
  678. static int
  679. store_jump(from, opcode, to)
  680.     char               *from, *to;
  681.     char                opcode;
  682. {
  683.     from[0] = opcode;
  684.     from[1] = (to - (from + 3)) & 0377;
  685.     from[2] = (to - (from + 3)) >> 8;
  686.     return 1; /* ????? I don't know what this guy was thinking ??? */
  687. }
  688.  
  689. /* Open up space at char FROM, and insert there a jump to TO.
  690.    CURRENT_END gives te end of the storage no in use,
  691.    so we know how much data to copy up.
  692.    OP is the opcode of the jump to insert.
  693.   
  694.    If you call this function, you must zero out pending_exact.  */
  695.  
  696. static int
  697. insert_jump(op, from, to, current_end)
  698.     char                op;
  699.     char               *from, *to, *current_end;
  700. {
  701.     register char      *pto = current_end + 3;
  702.     register char      *pfrom = current_end;
  703.  
  704.     while (pfrom != from)
  705.     *--pto = *--pfrom;
  706.     store_jump(from, op, to);
  707.     return 1;
  708. }
  709.  
  710.  
  711. /* Given a pattern, compute a fastmap from it.
  712.  The fastmap records which of the (1 << BYTEWIDTH) possible characters
  713.  can start a string that matches the pattern.
  714.  This fastmap is used by re_search to skip quickly over totally implausible text.
  715.   
  716.  The caller must supply the address of a (1 << BYTEWIDTH)-byte data area
  717.  as bufp->fastmap.
  718.  The other components of bufp describe the pattern to be used.  */
  719.  
  720. void
  721. re_compile_fastmap(bufp)
  722.     struct re_pattern_buffer *bufp;
  723. {
  724.     unsigned char      *pattern = (unsigned char *)bufp->buffer;
  725.     int                 size = bufp->used;
  726.     register char      *fastmap = bufp->fastmap;
  727.     register unsigned char *p = pattern;
  728.     register unsigned char *pend = pattern + size;
  729.     register int        j;
  730.     unsigned char      *translate = (unsigned char *)bufp->translate;
  731.  
  732.     unsigned char      *stackb[NFAILURES];
  733.     unsigned char     **stackp = stackb;
  734.  
  735.     bzero(fastmap, (1 << BYTEWIDTH));
  736.     bufp->fastmap_accurate = 1;
  737.     bufp->can_be_null = 0;
  738.  
  739.     while (p) {
  740.     if (p == pend) {
  741.         bufp->can_be_null = 1;
  742.         break;
  743.     }
  744. #ifdef SWITCH_ENUM_BUG
  745.     switch ((int)((enum regexpcode) * p++))
  746. #else
  747.     switch ((enum regexpcode) * p++)
  748. #endif
  749.     {
  750.     case exactn:
  751.         if (translate)
  752.         fastmap[translate[p[1]]] = 1;
  753.         else
  754.         fastmap[p[1]] = 1;
  755.         break;
  756.  
  757.     case begline:
  758.     case before_dot:
  759.     case at_dot:
  760.     case after_dot:
  761.     case begbuf:
  762.     case endbuf:
  763.     case wordbound:
  764.     case notwordbound:
  765.     case wordbeg:
  766.     case wordend:
  767.         continue;
  768.       case unused:
  769.         break;
  770.  
  771.     case endline:
  772.         if (translate)
  773.         fastmap[translate['\n']] = 1;
  774.         else
  775.         fastmap['\n'] = 1;
  776.         if (bufp->can_be_null != 1)
  777.         bufp->can_be_null = 2;
  778.         break;
  779.  
  780.     case finalize_jump:
  781.     case maybe_finalize_jump:
  782.     case jump:
  783.     case dummy_failure_jump:
  784.         bufp->can_be_null = 1;
  785.         j = *p++ & 0377;
  786.         j += SIGN_EXTEND_CHAR(*(char *)p) << 8;
  787.         p += j + 1;        /* The 1 compensates for missing ++ above */
  788.         if (j > 0)
  789.         continue;
  790.     /*
  791.      * Jump backward reached implies we just went through the body of a
  792.      * loop and matched nothing. Opcode jumped to should be an
  793.      * on_failure_jump. Just treat it like an ordinary jump. For a *
  794.      * loop, it has pushed its failure point already; if so, discard that
  795.      * as redundant.  
  796.      */
  797.         if ((enum regexpcode) * p != on_failure_jump)
  798.         continue;
  799.         p++;
  800.         j = *p++ & 0377;
  801.         j += SIGN_EXTEND_CHAR(*(char *)p) << 8;
  802.         p += j + 1;        /* The 1 compensates for missing ++ above */
  803.         if (stackp != stackb && *stackp == p)
  804.         stackp--;
  805.         continue;
  806.  
  807.     case on_failure_jump:
  808.         j = *p++ & 0377;
  809.         j += SIGN_EXTEND_CHAR(*(char *)p) << 8;
  810.         p++;
  811.         *++stackp = p + j;
  812.         continue;
  813.  
  814.     case start_memory:
  815.     case stop_memory:
  816.         p++;
  817.         continue;
  818.  
  819.     case duplicate:
  820.         bufp->can_be_null = 1;
  821.         fastmap['\n'] = 1;
  822.     case anychar:
  823.         for (j = 0; j < (1 << BYTEWIDTH); j++)
  824.         if (j != '\n')
  825.             fastmap[j] = 1;
  826.         if (bufp->can_be_null)
  827.         return;
  828.     /*
  829.      * Don't return; check the alternative paths so we can set
  830.      * can_be_null if appropriate.  
  831.      */
  832.         break;
  833.  
  834.     case wordchar:
  835.         for (j = 0; j < (1 << BYTEWIDTH); j++)
  836.         if (SYNTAX(j) == Sword)
  837.             fastmap[j] = 1;
  838.         break;
  839.  
  840.     case notwordchar:
  841.         for (j = 0; j < (1 << BYTEWIDTH); j++)
  842.         if (SYNTAX(j) != Sword)
  843.             fastmap[j] = 1;
  844.         break;
  845.  
  846. #ifdef emacs
  847.     case syntaxspec:
  848.         k = *p++;
  849.         for (j = 0; j < (1 << BYTEWIDTH); j++)
  850.         if (SYNTAX(j) == (enum syntaxcode) k)
  851.             fastmap[j] = 1;
  852.         break;
  853.  
  854.     case notsyntaxspec:
  855.         k = *p++;
  856.         for (j = 0; j < (1 << BYTEWIDTH); j++)
  857.         if (SYNTAX(j) != (enum syntaxcode) k)
  858.             fastmap[j] = 1;
  859.         break;
  860. #else
  861.     case syntaxspec:
  862.     case notsyntaxspec:
  863.         break;
  864. #endif                /* emacs */
  865.  
  866.     case charset:
  867.         for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
  868.         if (p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH))) {
  869.             if (translate)
  870.             fastmap[translate[j]] = 1;
  871.             else
  872.             fastmap[j] = 1;
  873.         }
  874.         break;
  875.  
  876.     case charset_not:
  877.     /* Chars beyond end of map must be allowed */
  878.         for (j = *p * BYTEWIDTH; j < (1 << BYTEWIDTH); j++)
  879.         if (translate)
  880.             fastmap[translate[j]] = 1;
  881.         else
  882.             fastmap[j] = 1;
  883.  
  884.         for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
  885.         if (!(p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH)))) {
  886.             if (translate)
  887.             fastmap[translate[j]] = 1;
  888.             else
  889.             fastmap[j] = 1;
  890.         }
  891.         break;
  892.     }
  893.  
  894.     /*
  895.      * Get here means we have successfully found the possible starting
  896.      * characters of one path of the pattern.  We need not follow this path
  897.      * any farther. Instead, look at the next alternative remembered in the
  898.      * stack. 
  899.      */
  900.     if (stackp != stackb)
  901.         p = *stackp--;
  902.     else
  903.         break;
  904.     }
  905. }
  906.  
  907.  
  908. /* Like re_search_2, below, but only one string is specified. */
  909. /* Modified to put size of match in matchsize by David Holscher */
  910. int
  911. re_search(pbufp, string, size, startpos, range, regs, matchsize)
  912.     struct re_pattern_buffer *pbufp;
  913.     char               *string;
  914.     int                 size, startpos, range;
  915.     struct re_registers *regs;
  916.     int                *matchsize;
  917. {
  918.     return re_search_2(pbufp, 0, 0, string, size, startpos, range, regs, size, matchsize);
  919. }
  920.  
  921. /* Like re_match_2 but tries first a match starting at index STARTPOS,
  922.    then at STARTPOS + 1, and so on.
  923.    RANGE is the number of places to try before giving up.
  924.    If RANGE is negative, the starting positions tried are
  925.     STARTPOS, STARTPOS - 1, etc.
  926.    It is up to the caller to make sure that range is not so large
  927.    as to take the starting position outside of the input strings.
  928.   
  929. The value returned is the position at which the match was found,
  930.  or -1 if no match was found,
  931.  or -2 if error (such as failure stack overflow).  */
  932. /* Modified to put size of match in matchsize by David Holscher */
  933.  
  934. int
  935. re_search_2(pbufp, string1, size1, string2, size2, startpos, range, regs, mstop, matchsize)
  936.     struct re_pattern_buffer *pbufp;
  937.     char               *string1, *string2;
  938.     int                 size1, size2;
  939.     int                 startpos;
  940.     register int        range;
  941.     struct re_registers *regs;
  942.     int                 mstop;
  943.     int                *matchsize;
  944. {
  945.     register char      *fastmap = pbufp->fastmap;
  946.     register unsigned char *translate = (unsigned char *)pbufp->translate;
  947.     int                 total = size1 + size2;
  948.     int                 val;
  949.  
  950.  /* Update the fastmap now if not correct already */
  951.     if (fastmap && !pbufp->fastmap_accurate)
  952.     re_compile_fastmap(pbufp);
  953.  
  954.  /*
  955.   * Don't waste time in a long search for a pattern that says it is anchored.  
  956.   */
  957.     if (pbufp->used > 0 && (enum regexpcode) pbufp->buffer[0] == begbuf
  958.     && range > 0) {
  959.     if (startpos > 0)
  960.         return -1;
  961.     else
  962.         range = 1;
  963.     }
  964.     while (1) {
  965.     /*
  966.      * If a fastmap is supplied, skip quickly over characters that cannot
  967.      * possibly be the start of a match. Note, however, that if the pattern
  968.      * can possibly match the null string, we must test it at each starting
  969.      * point so that we take the first null string we get.  
  970.      */
  971.  
  972.     if (fastmap && startpos < total && pbufp->can_be_null != 1) {
  973.         if (range > 0) {
  974.         register int        lim = 0;
  975.         register unsigned char *p;
  976.         int                 irange = range;
  977.  
  978.         if (startpos < size1 && startpos + range >= size1)
  979.             lim = range - (size1 - startpos);
  980.  
  981.         p = ((unsigned char *)
  982.         &(startpos >= size1 ? string2 - size1 : string1)[startpos]);
  983.  
  984.         if (translate) {
  985.             while (range > lim && !fastmap[translate[*p++]])
  986.             range--;
  987.         } else {
  988.             while (range > lim && !fastmap[*p++])
  989.             range--;
  990.         }
  991.         startpos += irange - range;
  992.         } else {
  993.         register unsigned char c;
  994.  
  995.         if (startpos >= size1)
  996.             c = string2[startpos - size1];
  997.         else
  998.             c = string1[startpos];
  999.         c &= 0xff;
  1000.         if (translate ? !fastmap[translate[c]] : !fastmap[c])
  1001.             goto advance;
  1002.         }
  1003.     }
  1004.     if (range >= 0 && startpos == total
  1005.         && fastmap && pbufp->can_be_null == 0)
  1006.         return -1;
  1007.  
  1008.     val = re_match_2(pbufp, string1, size1, string2, size2, startpos, regs, mstop);
  1009.     if (0 <= val) {
  1010.         if (val == -2)
  1011.         return -2;
  1012.         *matchsize = val;
  1013.         return startpos;
  1014.     }
  1015. #ifdef C_ALLOCA
  1016.     alloca(0);
  1017. #endif                /* C_ALLOCA */
  1018.  
  1019. advance:
  1020.     if (!range)
  1021.         break;
  1022.     if (range > 0)
  1023.         range--, startpos++;
  1024.     else
  1025.         range++, startpos--;
  1026.     }
  1027.     return -1;
  1028. }
  1029.  
  1030. #ifndef emacs            /* emacs never uses this */
  1031. int
  1032. re_match(pbufp, string, size, pos, regs)
  1033.     struct re_pattern_buffer *pbufp;
  1034.     char               *string;
  1035.     int                 size, pos;
  1036.     struct re_registers *regs;
  1037. {
  1038.     return re_match_2(pbufp, 0, 0, string, size, pos, regs, size);
  1039. }
  1040.  
  1041. #endif                /* emacs */
  1042.  
  1043. /* Maximum size of failure stack.  Beyond this, overflow is an error.  */
  1044.  
  1045. int                 re_max_failures = 2000;
  1046.  
  1047. static int          bcmp_translate();
  1048.  
  1049. /* Match the pattern described by PBUFP
  1050.    against data which is the virtual concatenation of STRING1 and STRING2.
  1051.    SIZE1 and SIZE2 are the sizes of the two data strings.
  1052.    Start the match at position POS.
  1053.    Do not consider matching past the position MSTOP.
  1054.   
  1055.    If pbufp->fastmap is nonzero, then it had better be up to date.
  1056.   
  1057.    The reason that the data to match are specified as two components
  1058.    which are to be regarded as concatenated
  1059.    is so this function can be used directly on the contents of an Emacs buffer.
  1060.   
  1061.    -1 is returned if there is no match.  -2 is returned if there is
  1062.    an error (such as match stack overflow).  Otherwise the value is the length
  1063.    of the substring which was matched.  */
  1064.  
  1065. int
  1066. re_match_2(pbufp, string1, size1, string2, size2, pos, regs, mstop)
  1067.     struct re_pattern_buffer *pbufp;
  1068.     unsigned char      *string1, *string2;
  1069.     int                 size1, size2;
  1070.     int                 pos;
  1071.     struct re_registers *regs;
  1072.     int                 mstop;
  1073. {
  1074.     register unsigned char *p = (unsigned char *)pbufp->buffer;
  1075.     register unsigned char *pend = p + pbufp->used;
  1076.  
  1077.  /* End of first string */
  1078.     unsigned char      *end1;
  1079.  
  1080.  /* End of second string */
  1081.     unsigned char      *end2;
  1082.  
  1083.  /* Pointer just past last char to consider matching */
  1084.     unsigned char      *end_match_1, *end_match_2;
  1085.     register unsigned char *d, *dend;
  1086.     register int        mcnt;
  1087.     unsigned char      *translate = (unsigned char *)pbufp->translate;
  1088.  
  1089.  /*
  1090.   * Failure point stack.  Each place that can handle a failure further down
  1091.   * the line pushes a failure point on this stack.  It consists of two char
  1092.   * *'s. The first one pushed is where to resume scanning the pattern; the
  1093.   * second pushed is where to resume scanning the strings. If the latter is
  1094.   * zero, the failure point is a "dummy". If a failure happens and the
  1095.   * innermost failure point is dormant, it discards that failure point and
  1096.   * tries the next one. 
  1097.   */
  1098.  
  1099.     unsigned char      *initial_stack[2 * NFAILURES];
  1100.     unsigned char     **stackb = initial_stack;
  1101.     unsigned char     **stackp = stackb, **stacke = &stackb[2 * NFAILURES];
  1102.  
  1103.  /*
  1104.   * Information on the "contents" of registers. These are pointers into the
  1105.   * input strings; they record just what was matched (on this attempt) by
  1106.   * some part of the pattern. The start_memory command stores the start of a
  1107.   * register's contents and the stop_memory command stores the end. 
  1108.   *
  1109.   * At that point, regstart[regnum] points to the first character in the
  1110.   * register, regend[regnum] points to the first character beyond the end of
  1111.   * the register, regstart_seg1[regnum] is true iff regstart[regnum] points
  1112.   * into string1, and regend_seg1[regnum] is true iff regend[regnum] points
  1113.   * into string1.  
  1114.   */
  1115.  
  1116.     unsigned char      *regstart[RE_NREGS];
  1117.     unsigned char      *regend[RE_NREGS];
  1118.     unsigned char       regstart_seg1[RE_NREGS], regend_seg1[RE_NREGS];
  1119.  
  1120.  /*
  1121.   * Set up pointers to ends of strings. Don't allow the second string to be
  1122.   * empty unless both are empty.  
  1123.   */
  1124.     if (!size2) {
  1125.     string2 = string1;
  1126.     size2 = size1;
  1127.     string1 = 0;
  1128.     size1 = 0;
  1129.     }
  1130.     end1 = string1 + size1;
  1131.     end2 = string2 + size2;
  1132.  
  1133.  /* Compute where to stop matching, within the two strings */
  1134.     if (mstop <= size1) {
  1135.     end_match_1 = string1 + mstop;
  1136.     end_match_2 = string2;
  1137.     } else {
  1138.     end_match_1 = end1;
  1139.     end_match_2 = string2 + mstop - size1;
  1140.     }
  1141.  
  1142.  /*
  1143.   * Initialize \) text positions to -1 to mark ones that no \( or \) has been
  1144.   * seen for.  
  1145.   */
  1146.  
  1147.     for (mcnt = 0; mcnt < sizeof(regend) / sizeof(*regend); mcnt++)
  1148.     regend[mcnt] = (unsigned char *)-1;
  1149.  
  1150.  /*
  1151.   * `p' scans through the pattern as `d' scans through the data. `dend' is
  1152.   * the end of the input string that `d' points within. `d' is advanced into
  1153.   * the following input string whenever necessary, but this happens before
  1154.   * fetching; therefore, at the beginning of the loop, `d' can be pointing at
  1155.   * the end of a string, but it cannot equal string2.  
  1156.   */
  1157.  
  1158.     if (pos <= size1)
  1159.     d = string1 + pos, dend = end_match_1;
  1160.     else
  1161.     d = string2 + pos - size1, dend = end_match_2;
  1162.  
  1163. /* Write PREFETCH; just before fetching a character with *d.  */
  1164. #define PREFETCH \
  1165.  while (d == dend)                            \
  1166.   { if (dend == end_match_2) goto fail;  /* end of string2 => failure */   \
  1167.     d = string2;  /* end of string1 => advance to string2. */       \
  1168.     dend = end_match_2; }
  1169.  
  1170.  /*
  1171.   * This loop loops over pattern commands. It exits by returning from the
  1172.   * function if match is complete, or it drops through if match fails at this
  1173.   * starting point in the input data. 
  1174.   */
  1175.  
  1176.     while (1) {
  1177.     if (p == pend)
  1178.     /* End of pattern means we have succeeded! */
  1179.     {
  1180.     /* If caller wants register contents data back, convert it to indices */
  1181.         if (regs) {
  1182.         regs->start[0] = pos;
  1183.         if (dend == end_match_1)
  1184.             regs->end[0] = d - string1;
  1185.         else
  1186.             regs->end[0] = d - string2 + size1;
  1187.         for (mcnt = 1; mcnt < RE_NREGS; mcnt++) {
  1188.             if (regend[mcnt] == (unsigned char *)-1) {
  1189.             regs->start[mcnt] = -1;
  1190.             regs->end[mcnt] = -1;
  1191.             continue;
  1192.             }
  1193.             if (regstart_seg1[mcnt])
  1194.             regs->start[mcnt] = regstart[mcnt] - string1;
  1195.             else
  1196.             regs->start[mcnt] = regstart[mcnt] - string2 + size1;
  1197.             if (regend_seg1[mcnt])
  1198.             regs->end[mcnt] = regend[mcnt] - string1;
  1199.             else
  1200.             regs->end[mcnt] = regend[mcnt] - string2 + size1;
  1201.         }
  1202.         }
  1203.         if (dend == end_match_1)
  1204.         return (d - string1 - pos);
  1205.         else
  1206.         return d - string2 + size1 - pos;
  1207.     }
  1208.     /* Otherwise match next pattern command */
  1209. #ifdef SWITCH_ENUM_BUG
  1210.     switch ((int)((enum regexpcode) * p++))
  1211. #else
  1212.     switch ((enum regexpcode) * p++)
  1213. #endif
  1214.     {
  1215.  
  1216.     /*
  1217.      * \( is represented by a start_memory, \) by a stop_memory. Both of
  1218.      * those commands contain a "register number" argument. The text
  1219.      * matched within the \( and \) is recorded under that number. Then,
  1220.      * \<digit> turns into a `duplicate' command which is followed by the
  1221.      * numeric value of <digit> as the register number. 
  1222.      */
  1223.  
  1224.     case start_memory:
  1225.         regstart[*p] = d;
  1226.         regstart_seg1[*p++] = (dend == end_match_1);
  1227.         break;
  1228.  
  1229.     case stop_memory:
  1230.         regend[*p] = d;
  1231.         regend_seg1[*p++] = (dend == end_match_1);
  1232.         break;
  1233.  
  1234.     case duplicate:
  1235.         {
  1236.         int                 regno = *p++;    /* Get which register to
  1237.                              * match against */
  1238.         register unsigned char *d2, *dend2;
  1239.  
  1240.         d2 = regstart[regno];
  1241.         dend2 = ((regstart_seg1[regno] == regend_seg1[regno])
  1242.              ? regend[regno] : end_match_1);
  1243.         while (1) {
  1244.         /* Advance to next segment in register contents, if necessary */
  1245.             while (d2 == dend2) {
  1246.             if (dend2 == end_match_2)
  1247.                 break;
  1248.             if (dend2 == regend[regno])
  1249.                 break;
  1250.             d2 = string2, dend2 = regend[regno];    /* end of string1 =>
  1251.                                  * advance to string2. */
  1252.             }
  1253.         /* At end of register contents => success */
  1254.             if (d2 == dend2)
  1255.             break;
  1256.  
  1257.         /*
  1258.          * Advance to next segment in data being matched, if
  1259.          * necessary 
  1260.          */
  1261.             PREFETCH;
  1262.  
  1263.         /* mcnt gets # consecutive chars to compare */
  1264.             mcnt = dend - d;
  1265.             if (mcnt > dend2 - d2)
  1266.             mcnt = dend2 - d2;
  1267.         /* Compare that many; failure if mismatch, else skip them. */
  1268.             if (translate ? bcmp_translate(d, d2, mcnt, translate) : bcmp(d, d2, mcnt))
  1269.             goto fail;
  1270.             d += mcnt, d2 += mcnt;
  1271.         }
  1272.         }
  1273.         break;
  1274.  
  1275.     case anychar:
  1276.     /* fetch a data character */
  1277.         PREFETCH;
  1278.     /* Match anything but a newline.  */
  1279.         if ((translate ? translate[*d++] : *d++) == '\n')
  1280.         goto fail;
  1281.         break;
  1282.  
  1283.     case charset:
  1284.     case charset_not:
  1285.         {
  1286.         /* Nonzero for charset_not */
  1287.         int                 not = 0;
  1288.         register int        c;
  1289.  
  1290.         if (*(p - 1) == (unsigned char)charset_not)
  1291.             not = 1;
  1292.  
  1293.         /* fetch a data character */
  1294.         PREFETCH;
  1295.  
  1296.         if (translate)
  1297.             c = translate[*d];
  1298.         else
  1299.             c = *d;
  1300.  
  1301.         if (c < *p * BYTEWIDTH
  1302.             && p[1 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
  1303.             not = !not;
  1304.  
  1305.         p += 1 + *p;
  1306.  
  1307.         if (!not)
  1308.             goto fail;
  1309.         d++;
  1310.         break;
  1311.         }
  1312.  
  1313.     case begline:
  1314.         if (d == string1 || d[-1] == '\n')
  1315.         break;
  1316.         goto fail;
  1317.  
  1318.     case endline:
  1319.         if (d == end2
  1320.          || (d == end1 ? (size2 == 0 || *string2 == '\n') : *d == '\n'))
  1321.         break;
  1322.         goto fail;
  1323.  
  1324.     /*
  1325.      * "or" constructs ("|") are handled by starting each alternative
  1326.      * with an on_failure_jump that points to the start of the next
  1327.      * alternative. Each alternative except the last ends with a jump to
  1328.      * the joining point. (Actually, each jump except for the last one
  1329.      * really jumps to the following jump, because tensioning the jumps
  1330.      * is a hassle.) 
  1331.      */
  1332.  
  1333.     /*
  1334.      * The start of a stupid repeat has an on_failure_jump that points
  1335.      * past the end of the repeat text. This makes a failure point so
  1336.      * that, on failure to match a repetition, matching restarts past as
  1337.      * many repetitions have been found with no way to fail and look for
  1338.      * another one.  
  1339.      */
  1340.  
  1341.     /*
  1342.      * A smart repeat is similar but loops back to the on_failure_jump so
  1343.      * that each repetition makes another failure point. 
  1344.      */
  1345.  
  1346.     case on_failure_jump:
  1347.         if (stackp == stacke) {
  1348.         unsigned char     **stackx;
  1349.  
  1350.         if (stacke - stackb > re_max_failures * 2)
  1351.             return -2;
  1352.         stackx = (unsigned char **)alloca(2 * (stacke - stackb)
  1353.                           * sizeof(char *));
  1354.         bcopy(stackb, stackx, (stacke - stackb) * sizeof(char *));
  1355.         stackp = stackx + (stackp - stackb);
  1356.         stacke = stackx + 2 * (stacke - stackb);
  1357.         stackb = stackx;
  1358.         }
  1359.         mcnt = *p++ & 0377;
  1360.         mcnt += SIGN_EXTEND_CHAR(*(char *)p) << 8;
  1361.         p++;
  1362.         *stackp++ = mcnt + p;
  1363.         *stackp++ = d;
  1364.         break;
  1365.  
  1366.     /*
  1367.      * The end of a smart repeat has an maybe_finalize_jump back. Change
  1368.      * it either to a finalize_jump or an ordinary jump. 
  1369.      */
  1370.  
  1371.     case maybe_finalize_jump:
  1372.         mcnt = *p++ & 0377;
  1373.         mcnt += SIGN_EXTEND_CHAR(*(char *)p) << 8;
  1374.         p++;
  1375.         {
  1376.         register unsigned char *p2 = p;
  1377.  
  1378.         /*
  1379.          * Compare what follows with the begining of the repeat. If we
  1380.          * can establish that there is nothing that they would both
  1381.          * match, we can change to finalize_jump 
  1382.          */
  1383.         while (p2 != pend
  1384.                && (*p2 == (unsigned char)stop_memory
  1385.                || *p2 == (unsigned char)start_memory))
  1386.             p2++;
  1387.         if (p2 == pend)
  1388.             p[-3] = (unsigned char)finalize_jump;
  1389.         else if (*p2 == (unsigned char)exactn
  1390.              || *p2 == (unsigned char)endline) {
  1391.             register int        c = *p2 == (unsigned char)endline ? '\n' : p2[2];
  1392.             register unsigned char *p1 = p + mcnt;
  1393.  
  1394.         /*
  1395.          * p1[0] ... p1[2] are an on_failure_jump. Examine what
  1396.          * follows that 
  1397.          */
  1398.             if (p1[3] == (unsigned char)exactn && p1[5] != c)
  1399.             p[-3] = (unsigned char)finalize_jump;
  1400.             else if (p1[3] == (unsigned char)charset
  1401.                  || p1[3] == (unsigned char)charset_not) {
  1402.             int                 not = p1[3] == (unsigned char)charset_not;
  1403.  
  1404.             if (c < p1[4] * BYTEWIDTH
  1405.               && p1[5 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
  1406.                 not = !not;
  1407.             /* not is 1 if c would match */
  1408.             /* That means it is not safe to finalize */
  1409.             if (!not)
  1410.                 p[-3] = (unsigned char)finalize_jump;
  1411.             }
  1412.         }
  1413.         }
  1414.         p -= 2;
  1415.         if (p[-1] != (unsigned char)finalize_jump) {
  1416.         p[-1] = (unsigned char)jump;
  1417.         goto nofinalize;
  1418.         }
  1419.     /*
  1420.      * The end of a stupid repeat has a finalize-jump back to the start,
  1421.      * where another failure point will be made which will point after
  1422.      * all the repetitions found so far. 
  1423.      */
  1424.  
  1425.     case finalize_jump:
  1426.         stackp -= 2;
  1427.  
  1428.     case jump:
  1429.     nofinalize:
  1430.         mcnt = *p++ & 0377;
  1431.         mcnt += SIGN_EXTEND_CHAR(*(char *)p) << 8;
  1432.         p += mcnt + 1;    /* The 1 compensates for missing ++ above */
  1433.         break;
  1434.  
  1435.     case dummy_failure_jump:
  1436.         if (stackp == stacke) {
  1437.         unsigned char     **stackx
  1438.         = (unsigned char **)alloca(2 * (stacke - stackb)
  1439.                        * sizeof(char *));
  1440.  
  1441.         bcopy(stackb, stackx, (stacke - stackb) * sizeof(char *));
  1442.         stackp = stackx + (stackp - stackb);
  1443.         stacke = stackx + 2 * (stacke - stackb);
  1444.         stackb = stackx;
  1445.         }
  1446.         *stackp++ = 0;
  1447.         *stackp++ = 0;
  1448.         goto nofinalize;
  1449.  
  1450.     case wordbound:
  1451.         if (d == string1    /* Points to first char */
  1452.         || d == end2    /* Points to end */
  1453.         || (d == end1 && size2 == 0))    /* Points to end */
  1454.         break;
  1455.         if ((SYNTAX(d[-1]) == Sword)
  1456.         != (SYNTAX(d == end1 ? *string2 : *d) == Sword))
  1457.         break;
  1458.         goto fail;
  1459.  
  1460.     case notwordbound:
  1461.         if (d == string1    /* Points to first char */
  1462.         || d == end2    /* Points to end */
  1463.         || (d == end1 && size2 == 0))    /* Points to end */
  1464.         goto fail;
  1465.         if ((SYNTAX(d[-1]) == Sword)
  1466.         != (SYNTAX(d == end1 ? *string2 : *d) == Sword))
  1467.         goto fail;
  1468.         break;
  1469.  
  1470.     case wordbeg:
  1471.         if (d == end2    /* Points to end */
  1472.         || (d == end1 && size2 == 0)    /* Points to end */
  1473.         ||SYNTAX(*(d == end1 ? string2 : d)) != Sword)    /* Next char not a
  1474.                                  * letter */
  1475.         goto fail;
  1476.         if (d == string1    /* Points to first char */
  1477.         || SYNTAX(d[-1]) != Sword)    /* prev char not letter */
  1478.         break;
  1479.         goto fail;
  1480.  
  1481.     case wordend:
  1482.         if (d == string1    /* Points to first char */
  1483.         || SYNTAX(d[-1]) != Sword)    /* prev char not letter */
  1484.         goto fail;
  1485.         if (d == end2    /* Points to end */
  1486.         || (d == end1 && size2 == 0)    /* Points to end */
  1487.         ||SYNTAX(d == end1 ? *string2 : *d) != Sword)    /* Next char not a
  1488.                                  * letter */
  1489.         break;
  1490.         goto fail;
  1491.  
  1492. #ifdef emacs
  1493.     case before_dot:
  1494.         if (((d - string2 <= (unsigned)size2)
  1495.          ? d - bf_p2 : d - bf_p1)
  1496.         <= point)
  1497.         goto fail;
  1498.         break;
  1499.  
  1500.     case at_dot:
  1501.         if (((d - string2 <= (unsigned)size2)
  1502.          ? d - bf_p2 : d - bf_p1)
  1503.         == point)
  1504.         goto fail;
  1505.         break;
  1506.  
  1507.     case after_dot:
  1508.         if (((d - string2 <= (unsigned)size2)
  1509.          ? d - bf_p2 : d - bf_p1)
  1510.         >= point)
  1511.         goto fail;
  1512.         break;
  1513.  
  1514.     case wordchar:
  1515.         mcnt = (int)Sword;
  1516.         goto matchsyntax;
  1517.  
  1518.     case syntaxspec:
  1519.         mcnt = *p++;
  1520.     matchsyntax:
  1521.         PREFETCH;
  1522.         if (SYNTAX(*d++) != (enum syntaxcode) mcnt)
  1523.         goto fail;
  1524.         break;
  1525.  
  1526.     case notwordchar:
  1527.         mcnt = (int)Sword;
  1528.         goto matchnotsyntax;
  1529.  
  1530.     case notsyntaxspec:
  1531.         mcnt = *p++;
  1532.     matchnotsyntax:
  1533.         PREFETCH;
  1534.         if (SYNTAX(*d++) == (enum syntaxcode) mcnt)
  1535.         goto fail;
  1536.         break;
  1537. #else
  1538.  
  1539.     case before_dot:
  1540.     case at_dot:
  1541.     case after_dot:
  1542.     case syntaxspec:
  1543.     case notsyntaxspec:
  1544.     break;
  1545.     
  1546.     case wordchar:
  1547.         PREFETCH;
  1548.         if (SYNTAX(*d++) == 0)
  1549.         goto fail;
  1550.         break;
  1551.  
  1552.     case notwordchar:
  1553.         PREFETCH;
  1554.         if (SYNTAX(*d++) != 0)
  1555.         goto fail;
  1556.         break;
  1557. #endif                /* not emacs */
  1558.  
  1559.  
  1560.     case unused:
  1561.         break;
  1562.     case begbuf:
  1563.         if (d == string1)    /* Note, d cannot equal string2 */
  1564.         break;        /* unless string1 == string2.  */
  1565.         goto fail;
  1566.  
  1567.     case endbuf:
  1568.         if (d == end2 || (d == end1 && size2 == 0))
  1569.         break;
  1570.         goto fail;
  1571.  
  1572.     case exactn:
  1573.     /*
  1574.      * Match the next few pattern characters exactly. mcnt is how many
  1575.      * characters to match. 
  1576.      */
  1577.         mcnt = *p++;
  1578.         if (translate) {
  1579.         do {
  1580.             PREFETCH;
  1581.             if (translate[*d++] != *p++)
  1582.             goto fail;
  1583.         }
  1584.         while (--mcnt);
  1585.         } else {
  1586.         do {
  1587.             PREFETCH;
  1588.             if (*d++ != *p++)
  1589.             goto fail;
  1590.         }
  1591.         while (--mcnt);
  1592.         }
  1593.         break;
  1594.     }
  1595.     continue;        /* Successfully matched one pattern command;
  1596.                  * keep matching */
  1597.  
  1598.     /* Jump here if any matching operation fails. */
  1599. fail:
  1600.     if (stackp != stackb)
  1601.     /* A restart point is known.  Restart there and pop it. */
  1602.     {
  1603.         if (!stackp[-2]) {    /* If innermost failure point is dormant,
  1604.                  * flush it and keep looking */
  1605.         stackp -= 2;
  1606.         goto fail;
  1607.         }
  1608.         d = *--stackp;
  1609.         p = *--stackp;
  1610.         if (d >= string1 && d <= end1)
  1611.         dend = end_match_1;
  1612.     } else
  1613.         break;        /* Matching at this starting point really
  1614.                  * fails! */
  1615.     }
  1616.     return -1;            /* Failure to match */
  1617. }
  1618.  
  1619. static int
  1620. bcmp_translate(s1, s2, len, translate)
  1621.     unsigned char      *s1, *s2;
  1622.     register int        len;
  1623.     unsigned char      *translate;
  1624. {
  1625.     register unsigned char *p1 = s1, *p2 = s2;
  1626.  
  1627.     while (len) {
  1628.     if (translate[*p1++] != translate[*p2++])
  1629.         return 1;
  1630.     len--;
  1631.     }
  1632.     return 0;
  1633. }
  1634.  
  1635.  
  1636. /* Entry points compatible with bsd4.2 regex library */
  1637.  
  1638. #ifndef emacs
  1639.  
  1640. static struct re_pattern_buffer re_comp_buf;
  1641.  
  1642. char               *
  1643. re_comp(s)
  1644.     char               *s;
  1645. {
  1646.     if (!s) {
  1647.     if (!re_comp_buf.buffer)
  1648.         return "No previous regular expression";
  1649.     return 0;
  1650.     }
  1651.     if (!re_comp_buf.buffer) {
  1652.     if (!(re_comp_buf.buffer = (char *)malloc(200)))
  1653.         return "Memory exhausted";
  1654.     re_comp_buf.allocated = 200;
  1655.     if (!(re_comp_buf.fastmap = (char *)malloc(1 << BYTEWIDTH)))
  1656.         return "Memory exhausted";
  1657.     }
  1658.     return re_compile_pattern(s, strlen(s), &re_comp_buf);
  1659. }
  1660.  
  1661. int
  1662. re_exec(s)
  1663.     char               *s;
  1664. {
  1665.     int                 len = strlen(s);
  1666.  
  1667.     return 0 <= re_search(&re_comp_buf, s, len, 0, len, 0);
  1668. }
  1669.  
  1670. #endif                /* emacs */
  1671.  
  1672.  
  1673. #ifdef test
  1674.  
  1675. #include <stdio.h>
  1676.  
  1677. /* Indexed by a character, gives the upper case equivalent of the character */
  1678.  
  1679. static char         upcase[0400] =
  1680. {000, 001, 002, 003, 004, 005, 006, 007,
  1681.  010, 011, 012, 013, 014, 015, 016, 017,
  1682.  020, 021, 022, 023, 024, 025, 026, 027,
  1683.  030, 031, 032, 033, 034, 035, 036, 037,
  1684.  040, 041, 042, 043, 044, 045, 046, 047,
  1685.  050, 051, 052, 053, 054, 055, 056, 057,
  1686.  060, 061, 062, 063, 064, 065, 066, 067,
  1687.  070, 071, 072, 073, 074, 075, 076, 077,
  1688.  0100, 0101, 0102, 0103, 0104, 0105, 0106, 0107,
  1689.  0110, 0111, 0112, 0113, 0114, 0115, 0116, 0117,
  1690.  0120, 0121, 0122, 0123, 0124, 0125, 0126, 0127,
  1691.  0130, 0131, 0132, 0133, 0134, 0135, 0136, 0137,
  1692.  0140, 0101, 0102, 0103, 0104, 0105, 0106, 0107,
  1693.  0110, 0111, 0112, 0113, 0114, 0115, 0116, 0117,
  1694.  0120, 0121, 0122, 0123, 0124, 0125, 0126, 0127,
  1695.  0130, 0131, 0132, 0173, 0174, 0175, 0176, 0177,
  1696.  0200, 0201, 0202, 0203, 0204, 0205, 0206, 0207,
  1697.  0210, 0211, 0212, 0213, 0214, 0215, 0216, 0217,
  1698.  0220, 0221, 0222, 0223, 0224, 0225, 0226, 0227,
  1699.  0230, 0231, 0232, 0233, 0234, 0235, 0236, 0237,
  1700.  0240, 0241, 0242, 0243, 0244, 0245, 0246, 0247,
  1701.  0250, 0251, 0252, 0253, 0254, 0255, 0256, 0257,
  1702.  0260, 0261, 0262, 0263, 0264, 0265, 0266, 0267,
  1703.  0270, 0271, 0272, 0273, 0274, 0275, 0276, 0277,
  1704.  0300, 0301, 0302, 0303, 0304, 0305, 0306, 0307,
  1705.  0310, 0311, 0312, 0313, 0314, 0315, 0316, 0317,
  1706.  0320, 0321, 0322, 0323, 0324, 0325, 0326, 0327,
  1707.  0330, 0331, 0332, 0333, 0334, 0335, 0336, 0337,
  1708.  0340, 0341, 0342, 0343, 0344, 0345, 0346, 0347,
  1709.  0350, 0351, 0352, 0353, 0354, 0355, 0356, 0357,
  1710.  0360, 0361, 0362, 0363, 0364, 0365, 0366, 0367,
  1711.  0370, 0371, 0372, 0373, 0374, 0375, 0376, 0377
  1712. };
  1713.  
  1714. main(argc, argv)
  1715.     int                 argc;
  1716.     char              **argv;
  1717. {
  1718.     char                pat[80];
  1719.     struct re_pattern_buffer buf;
  1720.     int                 i;
  1721.     char                c;
  1722.     char                fastmap[(1 << BYTEWIDTH)];
  1723.  
  1724.  /* Allow a command argument to specify the style of syntax.  */
  1725.     if (argc > 1)
  1726.     obscure_syntax = atoi(argv[1]);
  1727.  
  1728.     buf.allocated = 40;
  1729.     buf.buffer = (char *)malloc(buf.allocated);
  1730.     buf.fastmap = fastmap;
  1731.     buf.translate = upcase;
  1732.  
  1733.     while (1) {
  1734.     gets(pat);
  1735.  
  1736.     if (*pat) {
  1737.         re_compile_pattern(pat, strlen(pat), &buf);
  1738.  
  1739.         for (i = 0; i < buf.used; i++)
  1740.         printchar(buf.buffer[i]);
  1741.  
  1742.         putchar('\n');
  1743.  
  1744.         printf("%d allocated, %d used.\n", buf.allocated, buf.used);
  1745.  
  1746.         re_compile_fastmap(&buf);
  1747.         printf("Allowed by fastmap: ");
  1748.         for (i = 0; i < (1 << BYTEWIDTH); i++)
  1749.         if (fastmap[i])
  1750.             printchar(i);
  1751.         putchar('\n');
  1752.     }
  1753.     gets(pat);        /* Now read the string to match against */
  1754.  
  1755.     i = re_search(&buf, pat, strlen(pat), 0, strlen(pat), 0);
  1756.     printf("Match value %d.\n", i);
  1757.     }
  1758. }
  1759.  
  1760. #ifdef NOTDEF
  1761. print_buf(bufp)
  1762.     struct re_pattern_buffer *bufp;
  1763. {
  1764.     int                 i;
  1765.  
  1766.     printf("buf is :\n----------------\n");
  1767.     for (i = 0; i < bufp->used; i++)
  1768.     printchar(bufp->buffer[i]);
  1769.  
  1770.     printf("\n%d allocated, %d used.\n", bufp->allocated, bufp->used);
  1771.  
  1772.     printf("Allowed by fastmap: ");
  1773.     for (i = 0; i < (1 << BYTEWIDTH); i++)
  1774.     if (bufp->fastmap[i])
  1775.         printchar(i);
  1776.     printf("\nAllowed by translate: ");
  1777.     if (bufp->translate)
  1778.     for (i = 0; i < (1 << BYTEWIDTH); i++)
  1779.         if (bufp->translate[i])
  1780.         printchar(i);
  1781.     printf("\nfastmap is%s accurate\n", bufp->fastmap_accurate ? "" : "n't");
  1782.     printf("can %s be null\n----------", bufp->can_be_null ? "" : "not");
  1783. }
  1784.  
  1785. #endif
  1786.  
  1787. printchar(c)
  1788.     char                c;
  1789. {
  1790.     if (c < 041 || c >= 0177) {
  1791.     putchar('\\');
  1792.     putchar(((c >> 6) & 3) + '0');
  1793.     putchar(((c >> 3) & 7) + '0');
  1794.     putchar((c & 7) + '0');
  1795.     } else
  1796.     putchar(c);
  1797. }
  1798.  
  1799. error(string)
  1800.     char               *string;
  1801. {
  1802.     puts(string);
  1803.     exit(1);
  1804. }
  1805.  
  1806. #endif                /* test */
  1807.